package com.v1.web.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.v1.cache.CategoryCache;
import com.v1.lo.BaseLO;
import com.v1.lo.Statement;
import com.v1.model.Category;
import com.v1.model.Item;
import com.v1.model.Tag;

public class LianLianKanAction extends DefaultAction {

	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer categoryid = getInteger(request, "categoryid", 0);
		CategoryCache categoryCache = (CategoryCache) getBean("CategoryCache");
		if (categoryid == 0 || !categoryCache.contains(categoryid)) {
			return INDEX;
		}
		Category category = categoryCache.get(categoryid);
		setAttribute(request, "category", category);

		item(mapping, request, categoryid);
		Item item = (Item) getAttribute(request, "item");
		tags(category, item, request);

		String jsp = category.getJsp();
		return new ActionForward("", jsp, false, "");

	}

	private void tags(Category category, Item item, HttpServletRequest request) {
		BaseLO lo = (BaseLO) getBean("BaseLO");
		Tag tag = new Tag();
		tag.setCategoryid(category.getCategoryid());
		if (item != null) {
			tag.setItemid(item.getItemid());
		}
		List<Tag> tags = lo.queryForList(tag, Statement.Tag_getTags);
		setAttribute(request, "tags", tags);
	}

	private void item(ActionMapping mapping, HttpServletRequest request, int categoryid) {
		BaseLO lo = (BaseLO) getBean("BaseLO");
		String tag = getString(request, "tag", true, null);
		Tag cond = new Tag();
		if (StringUtils.isNotEmpty(tag)) {
			cond.setTag(tag);
		}

		int rowCount = lo.queryForCount(cond, Statement.Item_llk_getItemCount);
		if (rowCount != 0) {
			Integer pageNo = getInteger(request, "page", 1);
			cond.init(rowCount, pageNo);
			Item mark = null;
			List<Item> items = lo.queryForList(cond, Statement.Item_llk_getItems, mark);
			setAttribute(request, "items", items);
			setAttribute(request, "pageinfo", cond);
		}
	}

}